﻿using DevExpress.Pdf.Native;
using DevExpress.XtraEditors;
using ImageCalibModule;
using ImageDefine;
using ImageTaskModule;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TableModule;

namespace ImageCalibActionModule
{
    public partial class FormActioner : DevExpress.XtraEditors.XtraForm
    {
        ImageCalibHandeye imageCalibHandeye;

        public FormActioner()
        {
            InitializeComponent();
        }
        public FormActioner(ImageCalibHandeye imageCalibHandeyeIn)
        {
            InitializeComponent();
            imageCalibHandeye=imageCalibHandeyeIn;
        }

        private void FormActioner_Load(object sender, EventArgs e)
        {
            propertyGridControl1.SelectedObject = imageCalibHandeye;

            TableModule.FormDebugSimple formDebugSimple = new TableModule.FormDebugSimple();
            formDebugSimple.TopLevel = false;
            formDebugSimple.Size = panelControl1.Size;
            panelControl1.Controls.Add(formDebugSimple);
            formDebugSimple.Show();

            FrameManager.FrameManager.Camera1.SetGainAndShutter(imageCalibHandeye.iGain, imageCalibHandeye.dExporsureMs);

           
            textEdit曝光时间.Text = FrameManager.FrameManager.Camera1.GetShutter().ToString();
            textEdit增益.Text = FrameManager.FrameManager.Camera1.GetGain().ToString();

        }

        private void simpleButtonAutoCalib_Click(object sender, EventArgs e)
        {
            if (bStartLive)
            {
                bStartLive = false;
                simpleButtonGrab.Enabled = true;
                simpleButton2.Enabled = true;
            }
            Task.Factory.StartNew(() =>
            {
                FrameManager.FrameManager.Camera1.SetShutter(imageCalibHandeye.dExporsureMs);
                if (FrameManager.MachineStatus.Is4Axis)
                {
                    AutoCalibFunction();
                }
                else
                {
                    AutoCalibFunction3Axis();
                }
                
            });
        }
        public void AutoCalibFunction()
        {
            double x, y, dScore, dAngle;
            bool bOK = false;
            TableRunner table = TableManager.tableRunner;
            imageCalibHandeye.SetZOffSet(0);
            table.SetSpd("Calib");

            TableDataPosition postionStart = table.GetPosition("CalibCenter");
            ImageTask imageTask = ImageTaskModule.ImageTaskManager.ImageTask("Calib");
           
            postionStart.dXPos = postionStart.dXPos - imageCalibHandeye.Pitch;
            postionStart.dYPos = postionStart.dYPos - imageCalibHandeye.Pitch;
            TableDataPosition postionTemp = new TableDataPosition(postionStart);
            table.Go(postionStart);
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    
                    postionTemp.dXPos = postionStart.dXPos + imageCalibHandeye.Pitch * j;
                    postionTemp.dYPos = postionStart.dYPos + imageCalibHandeye.Pitch * i;
                    table.Go(postionTemp);
                    System.Threading.Thread.Sleep(1000);
                    imageTask.Run(smartDisplayControl1);
                   
                    if (imageTask.bResultOK)
                    {
                        imageCalibHandeye.dImageX[i * 3 + j] = imageTask.dResultX;
                        imageCalibHandeye.dImageY[i * 3 + j] = imageTask.dResultY;
                        imageCalibHandeye.dTableX[i * 3 + j] = postionTemp.dXPos;
                        imageCalibHandeye.dTableY[i * 3 + j] = postionTemp.dYPos;
                    }
                    else
                    {
                        XtraMessageBox.Show("图像识别失败，标定中断");
                        return;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }

           #region Angle1Detect

            TableDataPosition postionAngle1 = table.GetPosition("CalibCenter");
            table.Go(postionAngle1);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            if (imageTask.bResultOK)
                {
                imageCalibHandeye.dImageAngleX[0] = imageTask.dResultX;
                imageCalibHandeye.dImageAngleY[0] = imageTask.dResultY;
                imageCalibHandeye.dTableAngleX[0] = postionAngle1.dXPos;
                imageCalibHandeye.dTableAngleY[0] = postionAngle1.dYPos;
                imageCalibHandeye.dTableAngle[0] = postionAngle1.dUPos;
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }

            #endregion

           #region Angle2Detect
            TableDataPosition postionAngle2 = table.GetPosition("CalibCenter");
            postionAngle2.dUPos = postionAngle1.dUPos+20;
            table.Go(postionAngle2);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            if (imageTask.bResultOK)
            {
                imageCalibHandeye.dImageAngleX[1] = imageTask.dResultX;
                imageCalibHandeye.dImageAngleY[1] = imageTask.dResultY;
                imageCalibHandeye.dTableAngleX[1] = postionAngle2.dXPos;
                imageCalibHandeye.dTableAngleY[1] = postionAngle2.dYPos;
                imageCalibHandeye.dTableAngle[1] = postionAngle2.dUPos;
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }
            #endregion
            #region 标定
            string strImageType;
            int iImageWidth, iImageHeight;
            smartDisplayControl1.ho_Image.GetImagePointer1(out strImageType, out iImageWidth, out iImageHeight);
            imageCalibHandeye.CalibPara.StartImageWidth = iImageWidth;
            imageCalibHandeye.CalibPara.StartImageHeight = iImageHeight;
            imageCalibHandeye.CalibPara.StartCx = iImageWidth / 2;
            imageCalibHandeye.CalibPara.StartCy = iImageHeight / 2;
            imageCalibHandeye.CalibCamSelf();
            #endregion
            #region 验证
            TableDataPosition pos1 = table.GetPosition("CalibCenter");
            table.Go(pos1);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dCameraResultX, dCameraResultY;
            double dCameraTransX, dCameraTransY;
            if (imageTask.bResultOK)
            {
                dCameraResultX = imageTask.dResultX;
                dCameraResultY = imageTask.dResultY;
                imageCalibHandeye.TramImageToWorld(dCameraResultX, dCameraResultY,0.0,0.0,out dCameraTransX,out dCameraTransY);
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }

            double dTargetX, dTargetY, dTargetU;
            ImageDefine.MachineVisionToolKit.GetTargetPosForToolAndAngle(pos1.dXPos, pos1.dYPos, pos1.UPos, dCameraTransX, dCameraTransY, 0.0,
                dCameraTransX, dCameraTransY, 10,out dTargetX,out dTargetY,out dTargetU);
            TableDataPosition pos2 = table.GetPosition("CalibCenter");
            pos2.dXPos = dTargetX;
            pos2.dYPos = dTargetY;
            pos2.dUPos = dTargetU;
            table.Go(pos2);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dCameraResultX2, dCameraResultY2;
            double dCameraTransX2, dCameraTransY2;
            if (imageTask.bResultOK)
            {
                dCameraResultX2 = imageTask.dResultX;
                dCameraResultY2 = imageTask.dResultY;
                imageCalibHandeye.TramImageToWorld(dCameraResultX2, dCameraResultY2, 0.0, 0.0, out dCameraTransX2, out dCameraTransY2);
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }

            #endregion
            XtraMessageBox.Show("标定成功"+"Xdiff:"+ (dCameraTransX2 - dCameraTransX) + "Ydiff:" + (dCameraTransY2 - dCameraTransY));

            Action action = () =>
              {
                  propertyGridControl1.SelectedObject = null;
                  propertyGridControl1.SelectedObject = imageCalibHandeye;
              };
            propertyGridControl1.Invoke(action);
        }
        public void AutoCalibFunction3Axis()
        {
            double x, y, dScore, dAngle;
            bool bOK = false;
            TableRunner table = TableManager.tableRunner;
            imageCalibHandeye.SetZOffSet(0);
            table.SetSpd("Calib");

            TableDataPosition postionStart = table.GetPosition("CalibCenter");
            ImageTask imageTask = ImageTaskModule.ImageTaskManager.ImageTask("Calib");

            postionStart.dXPos = postionStart.dXPos - imageCalibHandeye.Pitch;
            postionStart.dYPos = postionStart.dYPos - imageCalibHandeye.Pitch;
            TableDataPosition postionTemp = new TableDataPosition(postionStart);
            table.Jump(postionStart);
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {

                    postionTemp.dXPos = postionStart.dXPos + imageCalibHandeye.Pitch * j;
                    postionTemp.dYPos = postionStart.dYPos + imageCalibHandeye.Pitch * i;
                    table.Go(postionTemp);
                    System.Threading.Thread.Sleep(1000);
                    imageTask.Run(smartDisplayControl1);

                    if (imageTask.bResultOK)
                    {
                        imageCalibHandeye.dImageX[i * 3 + j] = imageTask.dResultX;
                        imageCalibHandeye.dImageY[i * 3 + j] = imageTask.dResultY;
                        imageCalibHandeye.dTableX[i * 3 + j] = postionTemp.dXPos;
                        imageCalibHandeye.dTableY[i * 3 + j] = postionTemp.dYPos;
                    }
                    else
                    {
                        XtraMessageBox.Show("图像识别失败，标定中断");
                        return;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }

          
            #region 标定
            string strImageType;
            int iImageWidth, iImageHeight;
            smartDisplayControl1.ho_Image.GetImagePointer1(out strImageType, out iImageWidth, out iImageHeight);
            imageCalibHandeye.CalibPara.StartImageWidth = iImageWidth;
            imageCalibHandeye.CalibPara.StartImageHeight = iImageHeight;
            imageCalibHandeye.CalibPara.StartCx = iImageWidth / 2;
            imageCalibHandeye.CalibPara.StartCy = iImageHeight / 2;
            imageCalibHandeye.CalibCamSelfWithOutAngle();
            #endregion
            #region 验证
            TableDataPosition pos1 = table.GetPosition("CalibCenter");
            table.Go(pos1);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dCameraResultX, dCameraResultY;
            double dCameraTransX, dCameraTransY;
            if (imageTask.bResultOK)
            {
                dCameraResultX = imageTask.dResultX;
                dCameraResultY = imageTask.dResultY;
                imageCalibHandeye.TramImageToWorld(dCameraResultX, dCameraResultY, 0.0, 0.0, out dCameraTransX, out dCameraTransY);
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }

            double dTargetX, dTargetY, dTargetU;
            ImageDefine.MachineVisionToolKit.GetTargetPosForToolAndAngle(pos1.dXPos, pos1.dYPos, pos1.UPos, dCameraTransX, dCameraTransY, 0.0,
                dCameraTransX+10, dCameraTransY+10, 0, out dTargetX, out dTargetY, out dTargetU);
            TableDataPosition pos2 = table.GetPosition("CalibCenter");
            pos2.dXPos = dTargetX;
            pos2.dYPos = dTargetY;
            pos2.dUPos = dTargetU;
            table.Go(pos2);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dCameraResultX2, dCameraResultY2;
            double dCameraTransX2, dCameraTransY2;
            if (imageTask.bResultOK)
            {
                dCameraResultX2 = imageTask.dResultX;
                dCameraResultY2 = imageTask.dResultY;
                imageCalibHandeye.TramImageToWorld(dCameraResultX2, dCameraResultY2, 0.0, 0.0, out dCameraTransX2, out dCameraTransY2);
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }

            #endregion
            XtraMessageBox.Show("标定成功" + "Xdiff:" + ((dCameraTransX2 - dCameraTransX)-10).ToString("0.000") + "Ydiff:" + ((dCameraTransY2 - dCameraTransY)-10).ToString("0.000"));

            Action action = () =>
            {
                propertyGridControl1.SelectedObject = null;
                propertyGridControl1.SelectedObject = imageCalibHandeye;
            };
            propertyGridControl1.Invoke(action);
        }
        private void simpleButtonUpdateCenterPosition_Click(object sender, EventArgs e)
        {
            TableRunner table = TableManager.tableRunner;
            if (TableManager.tableActioner.tableDateGlabal.dicTableDataPos.Keys.Contains("CalibCenter"))
            {
                TableDataPosition tableDataPosition = TableManager.tableActioner.WhereTable();
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dXPos = tableDataPosition.dXPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dYPos = tableDataPosition.dYPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dZPos = tableDataPosition.dZPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dUPos = tableDataPosition.dUPos;
            }
            else
            {
                TableDataPosition tableDataPosition = new TableDataPosition();
                tableDataPosition.strDispalyName = "CalibCenter";
                tableDataPosition.Name = "CalibCenter";
                TableManager.globaltableData.TableSingleData.AddNewPos(tableDataPosition);
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dXPos = tableDataPosition.dXPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dYPos = tableDataPosition.dYPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dZPos = tableDataPosition.dZPos;
                TableManager.tableActioner.tableDateGlabal.dicTableDataPos["CalibCenter"].dUPos = tableDataPosition.dUPos;
            }
        }

        
        private void simpleButtonGrab_Click(object sender, EventArgs e)
        {
            //StopGetFlyImage();
            HalconDotNet.HImage hImage1 = new HalconDotNet.HImage(FrameManager.FrameManager.Camera1.GrabImage());
            smartDisplayControl1.ShowImage(hImage1);
        }
        bool bStartLive;
        Task taskLive;
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (bStartLive)
                return;
            bStartLive = true;
            simpleButtonGrab.Enabled = false;
            simpleButton2.Enabled = false;
            taskLive = Task.Factory.StartNew(() =>
            {
                HalconDotNet.HImage hImage1 = null;
                
                while (bStartLive)
                {
                    System.Threading.Thread.Sleep(20);
                    if (hImage1 != null)
                    {
                        hImage1.Dispose();
                    }
                    hImage1 = FrameManager.FrameManager.Camera1.GrabImage();
                    smartDisplayControl1.ShowImage(hImage1);
                }

            });
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            bStartLive = false;
            simpleButtonGrab.Enabled = true;
            simpleButton2.Enabled = true;
        }

        private void FormActioner_FormClosing(object sender, FormClosingEventArgs e)
        {
            bStartLive = false;
            if (taskLive != null)
            {
                taskLive.Wait();
            }
        }

        private void propertyGridControl1_CellValueChanged(object sender, DevExpress.XtraVerticalGrid.Events.CellValueChangedEventArgs e)
        {
            FrameManager.FrameManager.Camera1.SetGainAndShutter(imageCalibHandeye.iGain, imageCalibHandeye.dExporsureMs);
            textEdit曝光时间.Text = FrameManager.FrameManager.Camera1.GetShutter().ToString();
            textEdit增益.Text = FrameManager.FrameManager.Camera1.GetGain().ToString();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (bStartLive)
            {
                bStartLive = false;
                simpleButtonGrab.Enabled = true;
                simpleButton2.Enabled = true;
            }
            ImageTask imageTask = ImageTaskModule.ImageTaskManager.ImageTask("Calib");
            imageTask.Run(smartDisplayControl1);
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (bStartLive)
            {
                bStartLive = false;
                simpleButtonGrab.Enabled = true;
                simpleButton2.Enabled = true;
            }
            TableRunner table = TableManager.tableRunner;

            table.SetSpd("Calib");

            TableDataPosition postionStart = table.GetPosition("CalibCenter");
            table.Jump(postionStart);
           
            ImageTask imageTask = ImageTaskModule.ImageTaskManager.ImageTask("Calib");
            imageTask.Run(smartDisplayControl1);
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            Task.Factory.StartNew(() =>
            {
                AutoToolCalibFunction();
            });
        }
        public void AutoToolCalibFunction()
        {
            double x, y, dScore, dAngle;
            bool bOK = false;
            TableRunner table = TableManager.tableRunner;

            table.SetSpd("Calib");

            TableDataPosition postionStart = table.GetPosition("ToolCalib");
            ImageTask imageTask = ImageTaskModule.ImageTaskManager.ImageTask("ToolCalib");
            table.Go(postionStart);
            
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dBeforeX, dBeforeY;
            if (imageTask.bResultOK)
            {
                double dCurrentX = imageTask.dResultX;
                double dCurrentY = imageTask.dResultY;
                dBeforeX = imageTask.dResultX;
                dBeforeY = imageTask.dResultY;
                table.UpdateTool("Nozzle", dCurrentX, dCurrentY);
            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                return;
            }
            XtraMessageBox.Show("工具结果" +"ToolX:" + (table.tableActioner.tableDateGlabal.dicTableDataTool["Nozzle"].dX.ToString("0.000")) + "ToolY:" + (table.tableActioner.tableDateGlabal.dicTableDataTool["Nozzle"].dY).ToString("0.000"));
            table.SetTool("Nozzle");
            TableDataPosition position = table.WhereAtToolAndLocal();
            position.dUPos = position.dUPos - 30;
            table.Go(position);
            System.Threading.Thread.Sleep(1000);
            imageTask.Run(smartDisplayControl1);
            double dAfterX, dAfterY;
            if (imageTask.bResultOK)
            {
                dAfterX = imageTask.dResultX;
                dAfterY = imageTask.dResultY;

            }
            else
            {
                XtraMessageBox.Show("图像识别失败，标定中断");
                table.SetTool("Default");
                return;
            }
            table.SetTool("Default");

            XtraMessageBox.Show("标定成功" + "Xdiff:" + (dAfterX - dBeforeX) + "Ydiff:" + (dAfterY - dBeforeY));
        }

        private void simpleButton设定标定图像_Click(object sender, EventArgs e)
        {
            if (bStartLive)
            {
                bStartLive = false;
                simpleButtonGrab.Enabled = true;
                simpleButton2.Enabled = true;
            }
            FormImageTaskItem formImageTaskItem = new FormImageTaskItem(ImageTaskManager.ImageTask("Calib"));
            formImageTaskItem.TopLevel = false;
            formImageTaskItem.Size = this.Size;
            formImageTaskItem.Height = this.Height - 20;
            this.Controls.Add(formImageTaskItem);
            formImageTaskItem.Show();
            formImageTaskItem.BringToFront();
        }
    }
}
